#include "collectionbrowser.h"
#include "ui_collectionbrowser.h"

collectionBrowser::collectionBrowser(CollectionItemModel * model, QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::collectionBrowser)
{
    m_ui->setupUi(this);
    this->model = model;

    keyboard = new VirtualKeyboard();
    m_ui->verticalLayout->addWidget(keyboard);

    filterModel = new QSortFilterProxyModel();
    filterModel->setSourceModel(this->model);
    filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

    m_ui->listView->setModel(filterModel);
    m_ui->listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);   //required for flickcharm to work
    charm = new FlickCharm;
    charm->activateOn(m_ui->listView);

    connect(m_ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(itemClicked(QModelIndex)));
    connect(m_ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(clearFilter()));
    connect(m_ui->pushButton, SIGNAL(clicked()), model, SLOT(previous()));
    connect(m_ui->pushButton, SIGNAL(clicked()), this, SLOT(clearFilter()));

    connect(keyboard, SIGNAL(charSelected(QString)), this, SLOT(insertCharacter(QString)));
    connect(keyboard, SIGNAL(clearSelected()), this, SLOT(clearFilter()));
    connect(keyboard, SIGNAL(delSelected()), this, SLOT(delLastCharacter()));

    connect(m_ui->lineEdit, SIGNAL(textChanged(QString)), filterModel, SLOT(setFilterFixedString(QString)));

    this->setStyleSheet(" background-color: rgb(0, 0, 56);" \
        "font-family: 'DejaVu Sans';" \
        "font-size: 27pt;" \
        "font-weight: bold;" \
        "color: rgb(128,128,128);" \
        "margin: 0px;" \
        "padding: 0px;");

    /*
    this->m_ui->listView->setStyleSheet("background: rgb(0,0,56); " \
                                         "margin: 0px; padding: 0px;");
    */

    QPixmap pixmap(QString("svg/browser-arrow.png"));
    this->m_ui->pushButton->setIcon(pixmap);
    this->m_ui->pushButton->setIconSize(pixmap.size());

}

collectionBrowser::~collectionBrowser()
{
    delete m_ui;
}

void collectionBrowser::itemClicked(QModelIndex index)
{
    model->clickedCallback(filterModel->mapToSource(index));
}

void collectionBrowser::insertCharacter(const QString &character)
{
    m_ui->lineEdit->insert(character.toLower());
}

void collectionBrowser::clearFilter()
{
    m_ui->lineEdit->clear();
}

void collectionBrowser::delLastCharacter()
{
    m_ui->lineEdit->backspace();
}

void collectionBrowser::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

